<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.min.css" rel="stylesheet" />
        <link href="../../css/header.css" rel="stylesheet" />
		<style>
			html,
			body {
				height: 100%;
			}
			
			.mui-content {
				height: 100%;
				overflow: auto;
			}
			
			.red-point{
	          position: relative;
	        }
	
	        .red-point::before{
	          content: " ";
	          border: 5px solid #e690de;/*设置zi色*/
	          border-radius:5px;/*设置圆角*/
	          position: absolute;
	          z-index: 3000;
	          right: 0%;
	          margin-right: -10px;
	          margin-top: 0px;
	        }
            
            #msg-list {
            	height: 100%;
            	overflow: auto;
            	-webkit-overflow-scrolling: touch;
            }
            .msg-item {
            	padding: 8px;
            	clear: both;
            }
            .msg-item .mui-item-clear {
            	clear: both;
            }
            .msg-item .msg-user {
            	width: 38px;
            	height: 38px;
            	border: solid 1px #d3d3d3;
            	display: inline-block;
            	background: #fff;
            	border-radius: 3px;
            	vertical-align: top;
            	text-align: center;
            	/* float: left; */
            	padding: 3px;
            	color: #ddd;
            }
            
            .msg-item .msg-user-img{
            	width: 38px;
            	height: 38px;
            	display: inline-block;
            	border-radius: 3px;
            	vertical-align: top;
            	text-align: center;
            	/* float: left; */
            	color: #ddd;
            }
            
            .msg-item .msg-content {
            	display: inline-block;
            	border-radius: 5px;
            	border: solid 1px #d3d3d3;
            	background-color: #FFFFFF;
            	color: #333;
            	padding: 8px;
            	vertical-align: top;
            	font-size: 15px;
            	position: relative;
            	margin: 0px 8px;
            	max-width: 75%;
            	min-width: 35px;
            	/* float: left; */
            }
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav title">
			<h1 class="mui-title title-color" id="chat-title">uus</h1>
		</header>
        <script id='chat-list-template' type="text/template">
        	<% for(var i in chatSnapshotList){ var item=chatSnapshotList[i]; %>
                <li id="to_chat" friendId='<%=(item.friendId)%>' class="mui-table-view-cell mui-media">
                    <div class="mui-slider-right mui-disabled">
                        <button id="delete_msg" friendId='<%=(item.friendId)%>' class="mui-btn mui-btn-red">删除</button> 
                    </div> 
                    <div class="mui-slider-handle mui-media-body"> 
                        <img class="mui-media-object mui-pull-left" src="<%=(item.faceImage)%>"/>
                            <span class="<%=(item.isRead ? '' : 'red-point')%>">
                                <%=(item.nickname)%>
                            </span>
                        <p class="mui-ellipsis">
                            <%=(item.content)%>
                        </p> 
                    </div>
                </li>
        	<% } %>
        </script>
		<div class="mui-content">
            <div class="mui-indexed-list-search mui-input-row mui-search">
            	<input style="background-color: #fff;" type="search" 
                class="mui-input-clear mui-indexed-list-search-input" placeholder="搜索">
            </div>

			<ul id="ul_chatSnapshot" class="mui-table-view">
				
			</ul>
		</div>
		<script src="../../js/mui.min.js"></script>
        <script src="../../js/arttmpl.js"></script>
		<script src="../../js/app.js"></script>
        <script src="html5plus://ready"></script>  
		<script type="text/javascript">
			mui.init()
            template.config('escape', false);
			var myInfo;
            var chatSnapshot;
            // webscoket客户端
            window.Chat = {
                socket: null,
                uid: "",
                init: function () {
                    if (window.WebSocket) {
                        // 如果当前设备已建立连接，则不需要重新建立连接
                        if (Chat.socket != null && Chat.socket != undefined 
                            && Chat.socket.readyState == WebSocket.OPEN && Chat.uid == myInfo.id) {
                            return false;
                        }
                        // 初始化一个websocket连接
                        Chat.socket = new WebSocket(app.nettyServerUrl);
                        Chat.socket.onopen = Chat.wsOpen,
                        Chat.socket.onclose = Chat.wsClose,
                        Chat.socket.onerror = Chat.wsError,
                        Chat.socket.onmessage = Chat.wsOnMessage;
                        Chat.uid = myInfo.id;
                    } else {
                        alert("手机设备过旧")
                    }
                },
                chat: function (msg) {
                    // 只有websocket建立了连接才能发送消息
                    if (Chat.socket != null && Chat.socket != undefined
                        && Chat.socket.readyState == WebSocket.OPEN) {
                        Chat.sendMsg(msg);
                    } else {
                        // 先检查网络状态
                        var connectionStatus = plus.networkinfo.getCurrentType();
                        if (connectionStatus === 0 || connectionStatus === 1) {
                            app.showToast("无网络连接，不能发送消息", "error");
                            return false;
                        }
                        // 否则，重新建立连接，再发送消息
                        Chat.init();
                        // 获取开始时间的时间戳
                        var startTime = Date.parse(new Date());
                        // 阻塞直到webscoket连接建立完毕
                        while(Chat.socket != null){
                            var endTime = Date.parse(new Date());
                            if (endTime - startTime > 3000) {
                                app.showToast("发送失败,请重试", "error");
                                break;
                            }
                        }
                        // 重新发送消息
                        Chat.sendMsg(msg);
                    }
                },
                sendMsg: function (msg) {
                    var msgContent = JSON.parse(msg);
                    var chatMsg = msgContent.chatMsgBo;
                    // 获取消息内容
                    var content = chatMsg.content;
                    if (chatMsg.type == 'text') {
                        Chat.socket.send(msg);
                    } else if (chatMsg.type == 'image') {
                        // 将平台绝对路径转换成本地URL路径
                        var url = plus.io.convertAbsoluteFileSystem(chatMsg.content)
                        // 通过本地URL路径获取目录对象或文件对象
                        plus.io.resolveLocalFileSystemURL(url, function(entry) {
                            entry.file(function(evt) {
                                var reader = new plus.io.FileReader();
                                reader.readAsDataURL(evt);
                                reader.onloadend = function(e) {
                                    chatMsg.content = reader.result;
                                    var dataContent = new app.MsgContent(app.CHAT, chatMsg, null);
                                    Chat.socket.send(JSON.stringify(dataContent));
                                }
                            })
                        }, function(e) {
                            // 执行错误
                            mui.toast(e.message);
                        });
                    } else if (chatMsg.type == 'audio') {
                        // 通过本地URL路径获取目录对象或文件对象
                        plus.io.resolveLocalFileSystemURL(chatMsg.content, function(entry) {
                            entry.file(function(evt) {
                                var reader = new plus.io.FileReader();
                                reader.readAsDataURL(evt);
                                reader.onloadend = function(e) {
                                    chatMsg.content = reader.result;
                                    var dataContent = new app.MsgContent(app.CHAT, chatMsg, null);
                                    Chat.socket.send(JSON.stringify(dataContent));
                                }
                            })
                        }, function(e) {
                            // 执行错误
                            mui.toast(e.message);
                        });
                    }
                    // 获取好友的账号id
                    var friendId = chatMsg.receiverId
                    // 调用聊天页面的方法来刷新消息列表
                    var chatWebview = plus.webview.getWebviewById("chating-" + friendId);
                    var info = {
                    	sender: app.SELF,
                    	type: chatMsg.type, 
                    	content: content
                    };
                    chatWebview.evalJS("refreshMsgList('" + JSON.stringify(info) + "')");
                    // 保存聊天记录到本地(我发送给好友的消息)
                    app.saveChatRecord(chatMsg.senderId, friendId, app.SELF, chatMsg.type, content);
                    // 保存聊天快照
                    app.saveChatSnapshot(chatMsg.senderId, friendId, content, true);
                    // 重新渲染聊天快照列表
                    renderChatSnapshot();
                },
                wsOpen: function () {
                    console.log("websocket连接建立成功" + myInfo.id);
                    // 构建一个ChatMsg
                    var chatMsgBo = new app.ChatMsgBo(myInfo.id, null, null, null, null);
                    // 构建一个MsgContent
                    var msgContent = new app.MsgContent(app.CONNECT, chatMsgBo, null);
                    // 发送初始化连接的消息
                    Chat.socket.send(JSON.stringify(msgContent));
                    // 建立连接后，获取未签收的消息
                    getUnsignedMsg();
                    // 定时向后端发送心跳
                    setInterval(function() {
                        // 构建对象模型,用于保持心跳
                        var msgContent = new app.MsgContent(app.KEEPALIVE, null, null);
                        // 向后端发送心跳
                        Chat.socket.send(JSON.stringify(msgContent));
                        // 随心跳刷新聊天快照列表
                        renderChatSnapshot();
                    }, 50000);
                },
                wsError: function () {
                    console.log("websocket连接发生错误");
                },
                wsClose: function () {
                    console.log("websocket连接关闭");
                },
                wsOnMessage: function (e) {
                    console.log("收到的信息" + e.data)
                    // 转换收到的数据为chatMsg对象
                    var msgContent = JSON.parse(e.data);
                    var action = msgContent.action;
                    // 如果是重新拉取好友列表
                    if (action == app.PULL_FRIEND) {
                        // 刷新我的好友列表
                        var chatList = plus.webview.getWebviewById("chat-list");
                        mui.fire(chatList, "refresh_contact");
                        return false;
                    }
                    // 否则接收聊天信息
                    var chatMsg = msgContent.chatMsgBo;
                    // 获取消息内容和好友的账号id
                    var content = chatMsg.content;
                    var friendId = chatMsg.senderId;
                    var chatWebview = plus.webview.getWebviewById("chating-" + friendId);
                    var isRead = true;
                    if (chatWebview != null) {
                        var finfo = {
                        	sender: app.FRIEND,
                        	type: chatMsg.type, 
                        	content: content
                        };
                        // 调用wsWebview中的方法来发送消息
                        // 这里只能传字符串，所以需要把对象序列化为JSON字符串
                        chatWebview.evalJS("receive('" + JSON.stringify(finfo) + "')");
                    } else {
                        isRead = false;
                    }
                    
                    // 收到消息后，对消息进行签收
                    // 将后端返回来的消息id作为扩展参数
                    var msgContentSign = new app.MsgContent(app.SIGNED, null, chatMsg.msgId);
                    Chat.socket.send(JSON.stringify(msgContentSign))
                    
                    // 保存聊天记录到本地(接收到好友的消息)
                    app.saveChatRecord(chatMsg.receiverId, friendId, app.FRIEND, chatMsg.type, content);
                    // 保存聊天快照
                    app.saveChatSnapshot(chatMsg.receiverId, friendId, content, isRead);
                    // 重新渲染聊天快照列表
                    renderChatSnapshot();
                }
            };
            
            mui.plusReady(function () {
               // 获取我的个人信息
               myInfo = app.getUserGlobalInfo();
               // 初始化websocket
               Chat.init();
               // 加载列表
               renderChatSnapshot();
               var connectionStatus = plus.networkinfo.getCurrentType();
               if (connectionStatus === 0 || connectionStatus === 1) {
                   document.getElementById("chat-title").innerText = "雀信[离线]";
               }
               // 监听网络变化，设置对应的标题
               netChangeListener();
               // 添加自定义事件，初始化websocket
               window.addEventListener("init_websocket", function(){
               	Chat.init();
               });
               // 主动关闭websocket连接
               window.addEventListener("close_websocket", function(){
                   Chat.socket.close();
               });
               // 刷新聊天快照列表
               window.addEventListener("refresh_chat_snapshot", function(){
                   renderChatSnapshot();
               }); 
            });
            
            function netChangeListener() {
                document.addEventListener("netchange", function(){
                    var connectionStatus = plus.networkinfo.getCurrentType();
                    if (connectionStatus !== 0 && connectionStatus !== 1) {
                        document.getElementById("chat-title").innerText = "雀信";
                    } else {
                        document.getElementById("chat-title").innerText = "雀信[离线]";
                    }
                })
            }
            
            // 渲染聊天快照列表
            function renderChatSnapshot() {
                var myInfo = app.getUserGlobalInfo();
                // 获取聊天快照集合
                var chatSnapshotList = app.getChatSnapshot(myInfo.id);
                var chatSnapshot = document.getElementById("ul_chatSnapshot");
                // 通过map迭代数组，并动态地给对象元素添加新的属性
                var newChatSnapshot = chatSnapshotList.map(function(obj, index) {
                    // 新建一个对象
                    var newObj = {};
                    // 根据friendId从本地联系人列表获取联系人信息
                    var friendItem = app.getInfoByFriendId(obj.friendId);
                    // 好友的头像，如果不存在就用默认头像
                    var faceImage = friendItem.faceImage == "" ? app.defaultFace : friendItem.faceImage;
                    // 将原对象的属性赋值给新对象
                    newObj.friendId = obj.friendId;
                    newObj.content = obj.content;
                    newObj.isRead = obj.isRead;
                    // 将好友头像和昵称作为对象的新属性
                    newObj.nickname = friendItem.nickname;
                    newObj.faceImage = faceImage;
                    // 返回这个新对象
                    return newObj;
                });
                // 将聊天快照渲染到模板上
                chatSnapshot.innerHTML = template('chat-list-template', {
                	"chatSnapshotList": newChatSnapshot
                });
                // 批量绑定删除事件
                mui("#to_chat").on("tap", "#delete_msg", function() {
                    var friendId = this.getAttribute("friendId");
                    // 获取我的聊天快照
                    var chatSnapshotList = app.getChatSnapshot(myInfo.id);
                    for (var i = 0; i < chatSnapshotList.length; ++i) {
                        if (friendId == chatSnapshotList[i].friendId) {
                            // 删除该聊天快照
                            chatSnapshotList.splice(i, 1);
                            break;
                        }
                    }
                    // 更新聊天快照，并重新渲染列表
                    app.updateChatSnapshot(myInfo.id, chatSnapshotList);
                    renderChatSnapshot();
                });
                // 批量绑定事件，跳转到聊天界面
                mui("#ul_chatSnapshot").on("tap", "#to_chat", function() {
                    var friendId = this.getAttribute("friendId");
                    // 根据好友id查找对应的信息
                    var friendInfo = app.getInfoByFriendId(friendId);
                    var myInfo = app.getUserGlobalInfo();
                    var chatSnapshotList = app.getChatSnapshot(myInfo.id);
                    for (var i = 0; i < chatSnapshotList.length; ++i) {
                        if (friendId == chatSnapshotList[i].friendId) {
                            chatSnapshotList[i].isRead = true;
                            break;
                        }
                    }
                    mui.openWindow({
                        url: "../chat-list/chating.html",
                        id: "chating-" + friendInfo.id, // 每个好友的聊天页面都是唯一对应的
                        extras: {
                            friendInfo: friendInfo
                        }
                    })
                    // 更新聊天快照，并重新渲染列表
                    app.updateChatSnapshot(myInfo.id, chatSnapshotList);
                    renderChatSnapshot();
                })
            }
            
            // 重新上线后从服务端获取未签收的消息
            function getUnsignedMsg() {
                var myInfo = app.getUserGlobalInfo();
                var msgId = ",";
                mui.ajax(app.serverUrl + `/msg/unsignedMsg/${myInfo.id}`,{
                    data:{},
                    dataType:'json',// 服务器返回json格式数据
                    type:'get',// HTTP请求类型
                    timeout:10000,// 超时时间设置为10秒；
                    headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    success:function(data){
                        if (data.code == 200) {                            
                            var unsignedMsgList = data.data;
                            // 如果存在未签收的消息
                            if (unsignedMsgList.length > 0) {
                                for (var i = 0; i < unsignedMsgList.length; ++i) {
                                    var msgItem = unsignedMsgList[i];
                                    // 保存聊天记录到本地
                                    app.saveChatRecord(msgItem.acceptUserId, msgItem.sendUserId, 
                                    "zs", msgItem.type, msgItem.msg);
                                    // 保存聊天快照
                                    app.saveChatSnapshot(msgItem.acceptUserId, msgItem.sendUserId,
                                    msgItem.msg, false);
                                    // 拼接消息id
                                    msgId += msgItem.id + ",";
                                }
                                // 刷新聊天快照列表
                                renderChatSnapshot();
                                // 消息批量签收
                                var msgContentSign = new app.MsgContent(app.SIGNED, null, msgId);
                                Chat.socket.send(JSON.stringify(msgContentSign));
                            }
                        }
                    }
                });
            }
		</script>
	</body>

</html>